package com.zjc.lib_core.http;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 单例类 get方法返回retrofit对象
 * 二次封装OkHttp
 * 二次封装retrofit
 */
public class APIService {
    private OkHttpClient client;
    private Retrofit retrotif;//基于okhttp二次封装

    //封装OkHttp
    private void buildOkHttp(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(1, TimeUnit.MINUTES);//设置连接超时时长 单位分钟
        builder.readTimeout(1, TimeUnit.MINUTES);//设置读取数据时长 单位分钟
        //设置网络拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(interceptor);
        client = builder.build();
    }

    //封装retrofit
    private void buildRetrofit(){
        if (retrotif == null){
            //配置Retrofit
            buildOkHttp();
            Retrofit.Builder builder = new Retrofit.Builder();
            builder.client(client);//添加OkHttpClient对象
            //169.254.134.250
            builder.baseUrl("http://169.254.154.190/yoho/");//所有网络请求公共地址部分->
            //关联gson   用来解析json字符串
            builder.addConverterFactory(GsonConverterFactory.create());
            //关联rxjava
            builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
            retrotif = builder.build();
        }

    }

    public Retrofit getRetrotif(){
        if (retrotif == null){
            buildRetrofit();
        }
        return retrotif;
    }

    /**
     * 单例  懒汉式
     */
    private static APIService instance;
    private APIService(){}

    public static APIService getInstance(){
        if (instance == null){
            instance = new APIService();
        }

        return instance;
    }

}
